using UnityEngine;
using System.Collections;

public class Sprite
{
	protected float tilesH = 1.0f;//number of tiles horizontally, min(1)
	protected float tilesV = 1.0f;//number of tiles vertically, min(1)
	protected Vector2 startingTile = new Vector2();//starting from 0
	protected Vector2 tileOutput = new Vector2();//output variable, receives the square location on the texture
	int fps = 30;
	int count = 0;
	float frameH = 0;
	float frameV = 0;
	
	public Sprite(float tilesH, float tilesV, Vector2 startingTile)
	{
		this.tilesH = tilesH;
		this.tilesV = tilesV;
		this.startingTile = startingTile;
	}
	void Awake()
	{
		tileOutput.x = ((1.0f/tilesH)*startingTile.x);
		tileOutput.y = ((1.0f/tilesV)*startingTile.y);
	}
	
	// Use this for initialization
	void Start () 
	{
		
		
	}
	
	/// <summary>
	/// Update this instance.
	/// </summary>
	void Update () 
	{
		
	}
	
	/// <summary>
	/// Sets the current frame of the animation.
	/// </summary>
	public void SetFrame(Transform target,Vector2 currentFrame)
	{
		tileOutput.x = ((1.0f/tilesH)*currentFrame.x);
		tileOutput.y = ((1.0f/tilesV)*currentFrame.y);
		target.renderer.material.SetTextureOffset("_MainTex", tileOutput);
	}

	/// <summary>
	/// Animate this instance.
	/// </summary>
	public void Animate(Transform target)
	{
		count++;
		if (count % fps == 0)
		{
			if(frameV < tilesV)
			{
				if(frameH < tilesH)
				{
					SetFrame(target,new Vector2(frameH,frameV));
					Debug.Log(new Vector2(frameH,frameV));
					frameH++;
				}
				else if(frameV+1 != tilesV )
				{
					frameV++;
					frameH = 0.0f;
					SetFrame(target,new Vector2(frameH,frameV));
					frameH++;
				}
				else
				{
					frameH = 0;
					SetFrame(target,new Vector2(frameH,frameV));
					frameH++;
				}
			}
			else
			{
				frameV = 0;
			}
			count = 0;
		}
	}
	/// <summary>
	/// Animate the specified sprite, giving the line and total frames
	/// </summary>
	public void Animate(Transform target,float frameV, int totalFrames)
	{
		count++;
		if (count % fps == 0)
		{
			if(frameH < totalFrames)
			{
				SetFrame(target,new Vector2(frameH,frameV));
				Debug.Log(new Vector2(frameH,frameV));
				frameH++;
			}
			else
			{
				frameH = 0;
				SetFrame(target,new Vector2(frameH,frameV));
				frameH++;
			}
		}
	}
	
}
